package nrttest;

public class NRTTest  extends Thread {
	public static final int THREADS = 5;
	
	private int prio;
	public boolean running = true;
	public NRTTest(int prio)
	{
		this.prio = prio;
	}
	@Override
	public void run()
	{
		while(running)
		{
			if(prio == 3 || prio == 4)
			{
				System.out.println("Holy...I'm #" + prio + ". should wait here...");
				synchronized(this)
				{
					try {
						wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			System.out.println(""+prio+" Thread running");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args)
	{
		NRTTest[] tst = new NRTTest[THREADS];
		System.out.println("Thread creating...");
		for(int i = 0; i < THREADS; i++)
		{
			tst[i] = new NRTTest(i);
			tst[i].start();
		}
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		
		//System.out.println("Making 3 tst waiting...");
		System.out.println("Notifying tst #3...");
		synchronized(tst[3])
		{
			tst[3].notify();
		}
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		
		System.out.println("Packing up...");		
		for(int i = 0; i < THREADS; i++)
		{
			tst[i].running = false;
			tst[i].notifyAll();
		}
		for(int i = 0; i < THREADS; i++)
		{
			try {
				tst[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("End of program");
	}

}
